package eu.jba.denshijisho;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import eu.jba.denshijisho.dao.CardNoteDao;
import eu.jba.denshijisho.dao.NoteDao;
import eu.jba.denshijisho.entity.CardNote;
import eu.jba.denshijisho.entity.Note;
import eu.jba.denshijisho.util.Constants;

public class AddNoteActivity extends AbstractDenshiActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_note);
	}
	
	public void closeDialog(View view) {
		setResult(RESULT_CANCELED);
		finish();
	}
	
	public void saveNote(View view) {
		final Bundle bundle = getIntent().getExtras();
		final Integer cardId = (Integer)bundle.getInt(Constants.CARD_ID);
		final String noteText = ((EditText) findViewById(R.id.textNote))
				.getText().toString();
		final Note note = new Note(noteText);
		final int noteId = writeNote(note);
		connectCardNote(cardId, noteId);
		setResult(RESULT_OK);
		finish();
	}
	
	private int writeNote(Note note){
		final NoteDao noteDao = new NoteDao( this );
		noteDao.open();
		final Long id = noteDao.insert(note);
		noteDao.close();
		return id.intValue();
	}
	
	private void connectCardNote(Integer cardId, Integer noteId){
		final CardNote cardNote = new CardNote(cardId, noteId);
		final CardNoteDao cardNoteDao = new CardNoteDao( this );
		cardNoteDao.open();
		cardNoteDao.insert(cardNote);
		cardNoteDao.close();
	}
}
